#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "esp_wifi.h"
#include "esp_system.h"

static QueueHandle_t gpio_evt_queue = NULL;

static void IRAM_ATTR gpio_isr_handler(void *arg)
{
  uint32_t gpio_num = (uint32_t)arg;
  xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
}

static void boot_gpio_task(void *arg)
{
  uint32_t io_num;
  for (;;)
  {
    if (xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY))
    {
      printf("Restore all wifi set...\n");
      esp_wifi_restore();
      esp_restart();
    }
  }
}

void boot_gpio_init(void)
{
  gpio_config_t boot_config = {0};
  boot_config.intr_type = GPIO_INTR_NEGEDGE;
  boot_config.mode = GPIO_MODE_INPUT;
  boot_config.pin_bit_mask = (1ULL << GPIO_NUM_0);
  boot_config.pull_down_en = GPIO_PULLDOWN_DISABLE;
  boot_config.pull_up_en = GPIO_PULLUP_ENABLE;

  gpio_config(&boot_config);

  gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
  xTaskCreate(boot_gpio_task, "boot_gpio_task", 2048, NULL, 10, NULL);

  gpio_install_isr_service(0);
  gpio_isr_handler_add(GPIO_NUM_0, gpio_isr_handler, (void *)GPIO_NUM_0);
}